package com.kgc.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.api.goods.GoodsItemApi;
import com.kgc.bean.GoodsItem;
import com.kgc.constant.ElsConstant;
import com.kgc.service.ArrivalRemindService;
import com.kgc.util.RedisUtils;
import com.kgc.util.ResultBuildUtil;
import com.kgc.util.ReturnResult;
import com.kgc.util.SendSmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.document.StringField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Set;

/**
 * Created on 2021/6/23.
 * Author: lzy
 * Description:
 */
@Service
@Slf4j
public class ArrivalRemindServiceImpl implements ArrivalRemindService {


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Reference(timeout = 30000)
    private GoodsItemApi goodsItemApi;

    @Override
    public boolean judgeSetArrivalRemind(String goodsId, String phoneNo) {
        // 判断缓存中是否存在该用户数据
        return redisUtils.sHasKey(ElsConstant.ARRIVAL_REMIND_FIXED_HEAD + goodsId,phoneNo);
    }


    @Async("asyncServiceExecutor")
    @Override
    public void addArrivalRemind(String goodsId, String phoneNo) {
        String fixed = ElsConstant.ARRIVAL_REMIND_FIXED_HEAD + goodsId;
        redisUtils.sSet(fixed,phoneNo);
    }


    @Async("asyncServiceExecutor")
    @Override
    public void sendSmsToUserGoodsHasStock(String goodsId) {
        // 获取redis中缓存的
        Set<Object> objects = redisUtils.sGet(ElsConstant.ARRIVAL_REMIND_FIXED_HEAD + goodsId);

        Iterator<Object> iterator = objects.iterator();
        log.info("获取redis中缓存数据有：{}条",objects.size());


            // 遍历集合，并发送信息
            while (iterator.hasNext()){
                String next =  (String)iterator.next();
                // 发动短信
                SendSmsUtil.sendSms(next,goodsId);

                log.info(" ------ 发送给手机号：{} begin ------ ",next);

                redisUtils.setRemove(ElsConstant.ARRIVAL_REMIND_FIXED_HEAD + goodsId,next);

                log.info(" ------ 发送给手机号：{} end ------ ",next);
            }
    }

    @Override
    public GoodsItem queryselectGoodsByGoodsId(String goodsId) {

        return goodsItemApi.selectGoodsByGoodsId(goodsId);
    }
}
